<template>
    <div id="box">
        <div id="search">
            <el-form :inline="true" :model="roleSearch" class="demo-form-inline">
                <el-form-item label="角色名">
                    <el-input v-model="roleSearch.query.roleCh" placeholder="请输入角色名"></el-input>
                </el-form-item>
                <el-form-item label="权限标识">
                    <el-input v-model="roleSearch.query.roleEn" placeholder="请输入权限字符"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div id="header-bth">
            <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddRole">添加</el-button>
        </div>
        <div id="role-table">
            <el-table
                    :data="tableData"
                    stripe
                    height="310"
                    style="width:100%">
                <el-table-column label="角色名" prop="roleCh">
                </el-table-column>

                <el-table-column label="权限标识" prop="roleEn">
                </el-table-column>

                <el-table-column label="描述" prop="comments">
                </el-table-column>

                <el-table-column label="创建时间" width="200px" prop="createTime">
                </el-table-column>

                <el-table-column label="操作" width="280px">
                    <template slot-scope="scope">
                        <el-button
                                icon="el-icon-edit"
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">
                        </el-button>

                        <el-popconfirm title="确定删除吗？" @confirm="deleteRole(scope.$index, scope.row)">
                            <el-button
                                    slot="reference"
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>
                        <el-button
                                size="mini"
                                type="success"
                                @click="handleAuth(scope.$index, scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div id="nav-page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="pageSizes"
                    :page-size="roleSearch.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--添加 编辑角色信息弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
            <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
                <el-input v-model="roleForm.roleId" autocomplete="off" v-show="false"></el-input>
                <el-form-item label="角色名" prop="roleCh">
                    <el-input v-model="roleForm.roleCh" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleEn">
                    <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="comments">
                    <el-input v-model="roleForm.comments" show-word-limit maxlength="100" type="textarea"
                              :autosize="{ minRows: 5, maxRows: 10 }" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
        <!--分配权限-->
        <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearTree">
            <el-tree
                    ref="tree"
                    :data="treeData"
                    show-checkbox
                    accordion
                    node-key="id"
                    :default-checked-keys="defaultCheckedKeys"
                    :default-expand-all="false"
                    :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRolePermissions">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {
        addPermissionsByRoleId,
        deleteRoleById,
        getPermissionsByRoleId,
        getRoleById,
        roleList,
        saveUpdate
    } from "@/api/role";
    import {getPermissionList} from "@/api/permission";
    import {listToTree} from "@/utils/treeUtil";

    export default {
        name: "RoleView",
        data() {
            return {
                tableData: [],
                pageSizes: [5, 10, 15],
                total: 10,
                roleId: '',
                addRoleFormVisible: false,
                authTreeVisible: false,
                authTreeCheckedKeys: [],
                defaultCheckedKeys: [],
                dialogTitle: '',
                roleForm: {},
                roleSearch: {  // 搜索数据
                    limit: 5,
                    page: 1,
                    query: {
                        roleCh: '',
                        roleEn: ''
                    }
                },
                roleRules: {
                    roleCh: [{required: true, message: '请输入角色名', trigger: 'blur'}],
                    roleEn: [{required: true, message: '请输入角色标识', trigger: 'blur'}]
                },
                defaultProps: {
                    children: 'children',
                    label: 'title'
                },
                /*权限树形结构数据*/
                treeData: []

            }
        },
        methods: {
            // 编辑角色
            handleEdit(index, row) {
                this.dialogTitle = "编辑角色"
                this.addRoleFormVisible = true
                //  发送异步请求 根据角色id查询角色信息 实现数据回显
                let rid = row.roleId
                getRoleById(rid).then(res => {
                    if (res.code == 0) {
                        this.roleForm = res.data
                    }
                })
            },
            // 删除角色
            deleteRole(index, row) {
                // 发送异步请求 根据角色id 删除角色信息
                let rid = row.roleId
                deleteRoleById(rid).then(res => {
                    if (res.code == 0) {
                        this.$message.success(res.message);
                        this.list(this.roleSearch);
                    }
                })
            },
            saveOrUpdate() {
                this.$refs.roleInfo.validate(valid => {
                    if (!valid) {
                        this.$message.warning("请输入必要数据")
                        return
                    }
                    //  发送异步请求   实现角色的添加或修改    roleId
                    saveUpdate(this.roleForm).then(res => {
                        if (res.code == 0) {
                            this.$message.success(res.message)
                            this.list(this.roleSearch);
                            this.addRoleFormVisible = false
                        }
                    })
                })

            },
            /*分配权限*/
            async handleAuth(index, row) {
                // 显示权限分配弹出层
                this.authTreeVisible = true
                this.roleId = row.roleId
                // 发送异步请求 渲染 权限树形结构
                await getPermissionList().then(res => {
                    if (res.code == 0) {
                        // 将返回数据处理成  tree
                        this.treeData = listToTree(res.data)
                    }
                })

                // 根据角色id  回显当前角色的权限  isMenu = 2
                getPermissionsByRoleId(this.roleId).then(res => {
                    if (res.code == 0) {
                        this.defaultCheckedKeys = res.data   // []
                    }
                })

            },
            addRolePermissions() {
                // let HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()  // [1,2,3]
                //  let CheckedKeys = this.$refs.tree.getCheckedKeys()  //  [4,5,6]
                //  let newKeys = [...HalfCheckedKeys,...CheckedKeys]   // [1,2,3,4,5,6]

                this.authTreeCheckedKeys = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
                // 获取角色id
                let roleId = this.roleId;   //  rid = 1
                let ids = this.authTreeCheckedKeys  // [1,2,3,4,5]

                if (ids.length == 0) {
                    this.$message.warning("请给角色分配权限")
                    return
                }
                // 发送异步请求   添加角色权限
                addPermissionsByRoleId({roleId,ids}).then(res=>{
                    if (res.code==0){
                        this.$message.success(res.message)
                        this.authTreeVisible = false
                    }
                })

            },
            //清空权限回显数据
            clearTree() {
                this.defaultCheckedKeys = []
            },
            // 搜索角色
            onSearchSubmit() {
                this.roleSearch.page = 1
                this.list(this.roleSearch)
            },
            // 改变每页显示的条数触发
            handleSizeChange(val) {
                this.roleSearch.limit = val;
                this.list(this.roleSearch)
            },
            // 改变页码触发
            handleCurrentChange(val) {
                this.roleSearch.page = val;
                this.list(this.roleSearch)
            },
            // 显示弹出层
            showAddRole() {
                this.dialogTitle = "添加角色"
                this.addRoleFormVisible = true
            },
            //清空校验规则
            clearInfo() {
                this.roleForm = {}
                this.$refs.roleInfo.clearValidate()
            },
            // 加载角色列表
            list(searchFrom) {
                roleList(searchFrom).then(res => {
                    if (res.code == 0) {
                        this.tableData = res.data.pageData
                        this.total = res.data.total
                    }
                })
            }

        },
        created() {
            // 查询角色列表
            this.list(this.roleSearch)
        }
    }
</script>

<style scoped>

    #box {
        width: 95%;
        margin: 5px auto 0;
    }

    #search {
        width: 100%;
        height: 50px;
        padding-bottom: 20px;
        margin-top: 50px;
        margin-bottom: 20px;
        border-bottom: 1px solid #eee;
    }

    #header-bth {
        margin-bottom: 25px;
    }

    .el-button {
        margin-left: 5px;
        margin-right: 5px;
    }

    #nav-page {
        margin-top: 10px;
    }
</style>

